package com.easy.threads.actuator;


import com.easy.common.IWork;
import com.easy.config.log.MyLog;
import com.easy.threads.factory.ThreadFactory;
import com.easy.threads.singleton.Constant;
import com.easy.threads.singleton.WarehouseSingleton;
import com.easy.utils.PartitionJobStatus;

import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;

/**
 * 描述: 监听空闲线程与待执行任务
 *
 * @author gwj
 * @date 2023年12月14日 9:54
 */

public class Monitor extends Thread {

    private boolean status = true;

    private final String partition;

    private IWork work;

    private boolean waitFlag = true;

    public Monitor(String partitionKey) {
        MyLog.getLogger().log(Level.INFO, "创建监听线程，监听分区:{}", partitionKey);
        this.partition = partitionKey;
    }

    public void kill() {
        this.status = false;
    }

    public IWork getWork() {
        return work;
    }

    public void setWork(IWork work) {
        this.work = work;
    }


    @Override
    public void run() {

        while (status) {
            partitionOfDetectionTasks();
            waitFlag = true;
            doProcess();
            //没有空闲线程，或者没有待执行任务，等待五秒后继续监听
            if (waitFlag) {
                ThreadFactory.sleep(Constant.MONITOR_WAIT_TIME);
            }

            MyLog.getLogger().log(Level.INFO,"监听任务池中是否有待执行任务");
        }

        MyLog.getLogger().log(Level.INFO,"停止{}分区任务池",this.partition);
    }

    private void doProcess() {
        if (getWork() != null) {
            callJob();
        } else {
            //扫描任务池中的任务
            IWork work = WarehouseSingleton.WAREHOUSE_SINGLETON.getInstance().getWork(partition);
            if (work != null) {
                //根据分区key扫描是否有空闲线程
                setWork(work);
                callJob();
            }else{
                //判断任务分区状态，如果任务分区状态为停止状态，将分区任务池中的任务执行结束后，结束任务池中的所有job，然后停止监听任务
                boolean parStatus = PartitionJobStatus.getStatus(partition);
                if(!parStatus){
                    //获取任务
                    Job job = ThreadFactory.getJob(partition);
                    if(job != null){
                        //关闭任务
                        job.kill();
                        return;
                    }
                    //任务池中任务为空，修改分区状态为立即停止
                    PartitionJobStatus.stopImmediately(partition);
                }
            }
        }

    }

    private void callJob() {
        Job job = ThreadFactory.getJob(partition);
        if (job != null) {
            //设置当前线程状态为运行中
            job.setJobStatus(Constant.THREAD_STATUS_RUN);
            //设置具体执行类
            job.setWork(getWork());
            //唤醒线程
            job.jobNotify();
            setWork(null);
            waitFlag = false;
        }
    }

    /**
     * 描述 : 判断当前分区是否正常运行，如果为停止状态，停止当前分区监听任务，清空分区任务池
     * @author gwj
     * @date 2024/11/25 14:49
     */
    private void partitionOfDetectionTasks(){
        String partitionStatus = PartitionJobStatus.getStatusFlag(partition);
        if(PartitionJobStatus.STOP.equals(partitionStatus)){
            Map<String, CopyOnWriteArrayList<IWork>> workList = WarehouseSingleton.WAREHOUSE_SINGLETON.getInstance().getWorkList();
            CopyOnWriteArrayList<IWork> iWorks = workList.get(partition);
            //清空任务
            if(iWorks != null){
                iWorks.clear();
            }
            //删除分区
            workList.remove(partition);
            this.kill();
        }
    }
}
